//
//  SJPDepartmentTableViewController.m
//  SWS_Project00
//
//  Created by 马继鵬 on 17/3/8.
//  Copyright © 2017年 SWS. All rights reserved.
//

#import "SJPDepartmentTableViewController.h"
#import "SJPDepartModel.h"
#import "NSString+SJPString.h"


@interface SJPDepartmentTableViewController ()<UISearchControllerDelegate,UISearchResultsUpdating>
@property (strong,nonatomic) NSMutableArray *illList;
@property (strong,nonatomic) NSMutableArray *reasultList;
@property (strong,nonatomic) UISearchController* searchController ;
@property (strong,nonatomic) NSPredicate *searchPredicte;
@property (strong,nonatomic) NSString* text;
@end

static NSString* cell_ID = @"cell_ID";
@implementation SJPDepartmentTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //添加搜索框
    [self setupSearchBox];
    [self loadData];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cell_ID];
    self.reasultList = [NSMutableArray array];
    
    
}
#pragma
#pragma-设置搜索框
- (void)setupSearchBox
{
    UISearchController* searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
   
    _searchController = searchController;
    searchController.delegate = self;
    searchController.searchResultsUpdater = self;
    searchController.searchBar.placeholder = @"输入关键字";
    searchController.hidesNavigationBarDuringPresentation = NO;
    searchController.dimsBackgroundDuringPresentation = NO;
    searchController.searchBar.frame = CGRectMake(0, 0, 200, 44);
    //设置控制框外的文字
    [searchController.searchBar setValue:@""forKey:@"_cancelButtonText"];
    [[[searchController.searchBar.subviews.firstObject subviews]firstObject]removeFromSuperview];
    //设置颜色
    searchController.searchBar.barTintColor = [UIColor whiteColor];
//    self.tableView.tableHeaderView = searchController.searchBar;
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 44)];
    self.navigationItem.titleView = view;
    view.center =self.navigationItem.titleView.center;
//    self.navigationItem.titleView = searchController.searchBar;
    [view addSubview:searchController.searchBar];
//    searchController.searchBar.showsCancelButton = NO;
    
    
//    [self.searchController.searchBar sizeToFit];
    _reasultList = [NSMutableArray new];
    
}
#pragma
#pragma-数据加载
- (void)loadData
{
    NSString* path = [[NSBundle mainBundle]pathForResource:@"illsList.plist" ofType:nil];
    NSArray* arr = [[NSArray arrayWithContentsOfFile:path] mutableCopy];
    _illList = [NSMutableArray array];
    for(NSDictionary* dict in arr)
    {
        //拼接拼音
        NSMutableDictionary* dictM = [NSMutableDictionary new];
        NSString* string = [NSString SJP_transform:[dict valueForKey:@"name"]];
        NSString* text = [NSString stringWithFormat:@"%@ %@",[dict valueForKey:@"name"],string];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        [dictM setValue:text forKey:@"namePinyin"];
        [dictM setValue:[dict valueForKey:@"name"] forKey:@"name"];
        
        //转模型
        SJPDepartModel* model = [SJPDepartModel new];
        [model setValuesForKeysWithDictionary:dictM];
        
        [self.illList addObject:model];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma
#pragma-数据源方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    return   (!self.searchController.active) ?   _illList.count : _reasultList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_ID forIndexPath:indexPath];
    
   ;
    
    
     SJPDepartModel* model = (!self.searchController.active)?  _illList[indexPath.row] : _reasultList[indexPath.row];
    cell.textLabel.text = model.name;
    return cell;
}
#pragma
#pragma-数据代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     SJPDepartModel* model = (!self.searchController.active)?  _illList[indexPath.row] : _reasultList[indexPath.row];
//    NSLog(@"%@",model.name);
        if (self.titleBlock)
    {
        self.titleBlock(model.name);
        [self.navigationController popViewControllerAnimated:YES];
    }
}




#pragma
#pragma-搜索框代理方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    //清空结果数组中原有的数据
    [self.reasultList removeAllObjects];
    NSString* searchText = searchController.searchBar.text;
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if (searchText.length!=0 ) {
            
            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
            for (SJPDepartModel *model in self.illList) {
                
                NSString *tempStr = model.name;
                
                //----------->把所有的搜索结果转成成拼音
                NSString *pinyin = [self transformToPinyin:tempStr];
//                NSLog(@"pinyin--%@",pinyin);
                
                if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
                    //把搜索结果存放self.resultArray数组
                    [self.reasultList addObject:model];
                }
            }
        }else{
            self.reasultList = [NSMutableArray arrayWithArray:self.illList];
        }
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}



- (void)dealloc
{
    self.searchController.active = NO;
    self.searchController.searchBar.text = @"";
    
}

#pragma
#pragma-字符串拼接
- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];//区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
            
        }
        [allString appendString:@","];
        count ++;
        
    }
    
    NSMutableString *initialStr = [NSMutableString new];//拼音首字母
    
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    
    return allString;
}

@end
